package controllers

import (
	"beego/service"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/silenceper/wechat/v2"
	"github.com/silenceper/wechat/v2/cache"
	offConfig "github.com/silenceper/wechat/v2/officialaccount/config"
	"github.com/silenceper/wechat/v2/officialaccount/message"
	"net/http"
)

type WechatController struct {
	beego.Controller
}

func init() {
	//Go语言微信配置
}
func (c *WechatController) Callback() {
	// 使用memcache保存access_token，也可选择redis或自定义cache
	wc := wechat.NewWechat()
	memory := cache.NewMemory()
	cfg := &offConfig.Config{
		AppID:          "wx8ff3b88875289789",
		AppSecret:      "b4ca36c97e2217c2b088d62e491e6097",
		Token:          "php123456",
		EncodingAESKey: "gmybiqdnHYLOvxgb230QsrB1zPwOts0j8G8SnVsJ6JG",
		Cache:          memory,
	}
	officialAccount := wc.GetOfficialAccount(cfg)

	var rw http.ResponseWriter
	var req *http.Request
	// 传入request和responseWriter
	server := officialAccount.GetServer(req, rw)
	// 设置接收消息的处理方法
	server.SetMessageHandler(func(msg *message.MixMessage) *message.Reply {
		// 回复消息：演示回复用户发送的消息
		text := message.NewText(msg.Content)
		return &message.Reply{MsgType: message.MsgTypeText, MsgData: text}
	})

	// 处理消息接收以及回复
	err := server.Serve()
	if err != nil {
		fmt.Println(err)
		return
	}
	// 发送回复的消息
	server.Send()

	// JSON数据处理
	ret := service.ReturnMsg{
		Code: 200, Msg: "Success",
	}
	ret.Code = 10002
	c.Data["json"] = ret
	c.ServeJSON() // 对json进行序列化输出
	c.StopRun()
}
